package com.itheima;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//动态代理测试
public class ProxyTest {

    public static void main(String[] args) {
        //目标对象
        final TargetImpl target = new TargetImpl();

        //增强对象
        final Advice advice = new Advice();

        //返回值，就是动态代理对象，必须用接口去接收(JDK动态代理)
        Target proxy = (Target) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),//目标对象类加载器
                target.getClass().getInterfaces(),//目标对象相同的接口字节码数组
                new InvocationHandler() {
                    //调用代理对象的任何方法，实际上都是执行invoke方法
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        advice.before();
                        Object invoke = method.invoke(target, args);
                        advice.afterRunning();
                        return invoke;
                    }
                }
        );

        proxy.save();
    }
}
